<template>
  <el-dialog
    v-model="visible"
    title="复制维度"
    width="600px"
    destroy-on-close
    :before-close="handleBeforeClose"
  >
    <div v-loading="loading" class="copy-container">
      <!-- 源维度信息 -->
      <el-card class="copy-section-card">
        <template #header>
          <span class="section-title">源维度信息 (只读)</span>
        </template>
        <div class="source-info">
          <div class="info-item">
            <span class="info-label">📋 源维度</span>
            <div class="info-content">
              <div>维度代码: {{ sourceDimension.code || "-" }}</div>
              <div>维度名称: {{ sourceDimension.name || "-" }}</div>
              <div>所属模板: {{ sourceDimension.template_name || "-" }}</div>
            </div>
          </div>

          <div class="info-item">
            <span class="info-label">📊 配置概览</span>
            <div class="info-content">
              <div>最大分值: {{ sourceDimension.max_score || 0 }} 分</div>
              <div>权重系数: {{ sourceDimension.weight || 0 }}</div>
              <div>
                数据源类型:
                {{
                  getDataSourceTypeName(
                    sourceDimension.data_source_type ||
                      sourceDimension.data_source?.type
                  )
                }}
              </div>
              <div>
                计算类型:
                {{
                  getCalculationTypeName(
                    sourceDimension.calculation_type ||
                      sourceDimension.calculation?.type
                  )
                }}
              </div>
              <div>
                聚合模式:
                {{
                  getAggregationModeName(
                    sourceDimension.aggregation_mode ||
                      sourceDimension.aggregation?.mode
                  )
                }}
              </div>
            </div>
          </div>

          <div class="info-hint">ℹ️ 以上配置将完整复制到目标模板</div>
        </div>
      </el-card>

      <!-- 目标配置 -->
      <el-card class="copy-section-card">
        <template #header>
          <span class="section-title">目标配置</span>
        </template>
        <el-form
          ref="targetFormRef"
          :model="targetForm"
          label-width="100px"
          size="small"
        >
          <el-form-item
            label="目标模板 *"
            prop="target_template_id"
            :rules="[
              { required: true, message: '请选择目标模板', trigger: 'change' },
            ]"
          >
            <el-select
              v-model="targetForm.target_template_id"
              placeholder="选择目标模板"
              style="width: 100%"
            >
              <el-option
                v-for="template in templates"
                :key="template.id"
                :label="
                  template.name +
                  (template.id === sourceDimension.template_id
                    ? ' (当前模板)'
                    : '')
                "
                :value="template.id"
              ></el-option>
            </el-select>
            <div class="hint-text">
              ⚠️ 注意: 可以复制到同一模板,但需要不同的维度代码
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 新维度配置 -->
      <el-card class="copy-section-card">
        <template #header>
          <span class="section-title">新维度配置</span>
        </template>
        <el-form
          ref="newDimensionFormRef"
          :model="newDimensionForm"
          label-width="100px"
          size="small"
        >
          <el-form-item
            label="新维度代码"
            prop="new_code"
            :rules="[
              {
                required: !autoGenerate,
                message: '请输入新维度代码',
                trigger: 'blur',
              },
              {
                pattern: /^[a-zA-Z0-9_]+$/,
                message: '只能包含字母、数字和下划线',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="newDimensionForm.new_code"
              placeholder="请输入新维度代码"
              :disabled="autoGenerate"
              maxlength="30"
            ></el-input>
            <div class="hint-text">留空自动生成: {{ autoGeneratedCode }}</div>
          </el-form-item>

          <el-form-item
            label="新维度名称"
            prop="new_name"
            :rules="[
              {
                required: !autoGenerate,
                message: '请输入新维度名称',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="newDimensionForm.new_name"
              placeholder="请输入新维度名称"
              :disabled="autoGenerate"
              maxlength="50"
            ></el-input>
            <div class="hint-text">留空自动生成: {{ autoGeneratedName }}</div>
          </el-form-item>

          <el-form-item>
            <el-radio-group
              v-model="autoGenerate"
              @change="handleGenerateChange"
            >
              <el-radio :label="true">使用自动生成</el-radio>
              <el-radio :label="false">自定义命名</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 预览 -->
      <el-card class="copy-section-card">
        <template #header>
          <span class="section-title">预览</span>
        </template>
        <div class="preview-section">
          <div class="preview-title">📝 复制操作预览:</div>
          <div class="preview-content">
            <div>
              从: {{ sourceDimension.template_name || "-" }} /
              {{
                sourceDimension.dimension_code || sourceDimension.code || "-"
              }}
            </div>
            <div>到: {{ getTargetTemplateName() }} / {{ getNewCode() }}</div>
          </div>

          <div class="preview-title mt-3">将复制以下内容:</div>
          <div class="preview-details">
            <div>✓ 维度名称和描述</div>
            <div>✓ 最大分值 ({{ sourceDimension.max_score || 0 }})</div>
            <div>✓ 权重系数 ({{ sourceDimension.weight || 0 }})</div>
            <div>✓ 显示顺序 (重置为1)</div>
            <div>✓ 启用状态 (默认启用)</div>
            <div>✓ 数据源配置 (完整JSON)</div>
            <div>✓ 计算配置 (完整JSON)</div>
            <div>✓ 聚合配置 (完整JSON)</div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirmCopy">确认复制</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, onMounted, computed } from "vue";
import { ElMessage, ElForm } from "element-plus";
import { getDimensionDetail } from "../../../servers";
import { getTemplateList } from "../../../servers";
import { copyDimension } from "../../../servers";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  sourceDimensionId: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["success", "update:modelValue"]);

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const sourceDimension = ref<any>({});
const templates = ref<any[]>([]);
const autoGenerate = ref(true);

// 表单引用
const targetFormRef = ref<InstanceType<typeof ElForm>>();
const newDimensionFormRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const targetForm = ref<{
  target_template_id: number | string;
}>({
  target_template_id: "",
});

const newDimensionForm = ref({
  new_code: "",
  new_name: "",
});

// 自动生成的代码和名称
const autoGeneratedCode = computed(() => {
  const code =
    sourceDimension.value.dimension_code || sourceDimension.value.code;
  if (!code) return "";
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 10000);
  return `${code}_copy_${timestamp}_${random}`;
});

const autoGeneratedName = computed(() => {
  const name =
    sourceDimension.value.dimension_name || sourceDimension.value.name;
  if (!name) return "";
  return `${name}_副本`;
});

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (!val) {
      resetForm();
    }
  }
);

// 监听源维度ID变化
watch(
  () => props.sourceDimensionId,
  (id) => {
    if (id && visible.value) {
      fetchSourceDimension(id);
    }
  }
);

// 页面初始化
onMounted(() => {
  fetchTemplates();
});

// 获取源维度详情
const fetchSourceDimension = async (id: string | number) => {
  loading.value = true;
  try {
    const result = await getDimensionDetail({ dimension_id: Number(id) });
    if (result.code === 2000 && result.data) {
      sourceDimension.value = result.data;

      // 默认选择源维度所在的模板
      targetForm.value.target_template_id = result.data.template_id;
    } else {
      ElMessage.error(result.message || "获取源维度详情失败");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取源维度详情失败");
  } finally {
    loading.value = false;
  }
};

// 获取模板列表
const fetchTemplates = async () => {
  try {
    const { data } = await getTemplateList({ page_size: 100 });
    templates.value = data.list || data.items || [];
  } catch (error) {
    console.error("获取模板列表失败", error);
  }
};

// 重置表单
const resetForm = () => {
  targetForm.value = {
    target_template_id: "",
  };

  newDimensionForm.value = {
    new_code: "",
    new_name: "",
  };

  autoGenerate.value = true;

  if (targetFormRef.value) targetFormRef.value.resetFields();
  if (newDimensionFormRef.value) newDimensionFormRef.value.resetFields();
};

// 自动生成选项变化
const handleGenerateChange = () => {
  if (autoGenerate.value) {
    newDimensionForm.value.new_code = "";
    newDimensionForm.value.new_name = "";
  }
};

// 获取目标模板名称
const getTargetTemplateName = () => {
  const template = templates.value.find(
    (t) => t.id === targetForm.value.target_template_id
  );
  return template?.name || "";
};

// 获取新维度代码
const getNewCode = () => {
  return autoGenerate.value
    ? autoGeneratedCode.value
    : newDimensionForm.value.new_code;
};

// 获取数据源类型名称
const getDataSourceTypeName = (type) => {
  const typeMap = {
    single_table: "单表查询",
    multi_table: "多表关联",
    external_api: "外部接口",
  };
  return typeMap[type] || type || "-";
};

// 获取计算类型名称
const getCalculationTypeName = (type) => {
  const typeMap = {
    level_mapping: "级别映射",
    weighted_sum: "加权求和",
    threshold: "阈值判断",
    custom: "自定义公式",
  };
  return typeMap[type] || type || "-";
};

// 获取聚合模式名称
const getAggregationModeName = (mode) => {
  const modeMap = {
    max: "最大值",
    avg: "平均值",
    sum: "求和",
    priority: "优先级",
  };
  return modeMap[mode] || mode || "-";
};

// 表单验证
const validateForm = async () => {
  const targetValid = (await targetFormRef.value?.validate()) || false;
  const newDimensionValid =
    (await newDimensionFormRef.value?.validate()) || false;

  return targetValid && newDimensionValid;
};

// 确认复制
const handleConfirmCopy = async () => {
  if (!(await validateForm())) {
    return;
  }

  const copyData = {
    source_dimension_id: Number(props.sourceDimensionId),
    target_template_id: Number(targetForm.value.target_template_id),
    new_dimension_code: autoGenerate.value
      ? autoGeneratedCode.value
      : newDimensionForm.value.new_code,
    new_dimension_name: autoGenerate.value
      ? autoGeneratedName.value
      : newDimensionForm.value.new_name,
  };

  loading.value = true;
  try {
    const result = await copyDimension(copyData);
    if (result.code === 2000) {
      ElMessage.success("维度复制成功");
      emit("success");
      emit("update:modelValue", false);
    } else {
      ElMessage.error(result.message || "维度复制失败");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "维度复制失败");
  } finally {
    loading.value = false;
  }
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};

// 关闭前处理
const handleBeforeClose = () => {
  emit("update:modelValue", false);
  return true;
};
</script>

<style scoped lang="scss">
.copy-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.copy-section-card {
  margin-bottom: 16px;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-weight: 500;
  color: #1d2129;
}

.source-info {
  padding: 5px 0;
}

.info-item {
  margin-bottom: 15px;
}

.info-label {
  display: inline-block;
  font-weight: 500;
  margin-bottom: 5px;
  color: #1d2129;
}

.info-content {
  padding-left: 5px;
  line-height: 1.6;
}

.info-hint {
  margin-top: 10px;
  padding: 8px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
  color: #1890ff;
}

.hint-text {
  margin-top: 5px;
  font-size: 12px;
  color: #86909c;
}

.preview-section {
  padding: 5px 0;
}

.preview-title {
  font-weight: 500;
  margin-bottom: 8px;
  color: #1d2129;
}

.preview-content {
  padding-left: 5px;
  line-height: 1.6;
  margin-bottom: 10px;
}

.preview-details {
  padding-left: 5px;
  line-height: 1.6;
  font-size: 13px;
}

.mt-3 {
  margin-top: 15px;
}
</style>
